import json
from flask import Blueprint,  request, jsonify,render_template,session
from bt import Bt_api
from flask import current_app
from decorator import login_required
blueprint = Blueprint('/dns', __name__, url_prefix='/dns')

@blueprint.route("/", endpoint='/', methods=['GET', 'POST'])
@login_required
def dns():
    cdn=current_app.config['CDN']

    return render_template('dns.html',cdn=cdn)


# 获取域名
@blueprint.route("/get_domain", endpoint='get_domain', methods=['GET', 'POST'])
@login_required
def domain():
    if request.method == 'POST':
        # 实例化宝塔API对象
        bt_api=Bt_api(session.get('bt_url'),session.get('bt_key'))
        data = bt_api.getData_dns(session.get('siteId'))
        aa_data = {x["name"]: x for x in data if x["name"] != session.get('bt_web')}
        elements = []
        data2 = bt_api.GetDirBinding(session.get('siteId'))['binding']
    
        for key, value in aa_data.items():
            # 将字典中的元素添加到列表中
            elements.append(value)
        for item in data2:
            item['name'] = item['domain']
            del item['domain']   
       
        return jsonify(elements)
    return jsonify('非法请求')

# 添加域名
@blueprint.route("/AddDomain", endpoint='AddDomain', methods=['GET', 'POST'])
@login_required
def AddDomain():
    if request.method == 'POST':
       
        domain = request.form.get('domain')
        prot = request.form.get('prot')
        # 实例化宝塔API对象
        bt_api=Bt_api(session.get('bt_url'),session.get('bt_key'))
        data = bt_api.AddDomain(domain+":"+prot,session.get('bt_web'),session['siteId'])
        
       
        return jsonify(data['domains'][0])
    return jsonify('非法请求')


# 删除域名
@blueprint.route("/DelDomain", endpoint='DelDomain', methods=['GET', 'POST'])
@login_required
def DelDomain():
    domain = request.form.get('domain')
    port = request.form.get('port')
    if request.method == 'POST':
     
        
        # 实例化宝塔API对象
        bt_api=Bt_api(session.get('bt_url'),session.get('bt_key'))
        data = bt_api.DelDomain(session['siteId'],session.get('bt_web'),domain,port)
        
    
        
       
        return jsonify(data)
  
    return json.dumps({'code': 1, 'msg': '非法请求'})